/*
 *
 * 名称：鈢㔉奇门窗口
 * 功能：显示主窗口
 * 作者：清河张
 * 时间：2025.05.11
 *
 */

#include "xzqmwin.h"
#include "base/shuzi.h"
#include "ui_xzqmwin.h"
#include <QMessageBox>
#include <QClipboard>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFileDialog>
#include "xkfs/xkxing9.h"
#include "base/zhu.h"

using namespace QMDJ;


#define QMCFGJSONFILE "qm/config.json"
#define QMINDEX "INDEX"
#define QMARRAY "ARRAY"
#define QMINAME "NAME"
#define QMVALUE "VALUE"
#define QMMAP "MAP"
#define QMJIA "JIA"
#define QMYYDUN "YYDUN"
#define QMDINGJU "DINGJU"
#define QMJUZDY "JUZDY"
#define QMJIJUZDY "JIJUZDY"
#define QMTIAO "TIAO"
#define QMFA "FANGAN"

XZQMWIN::XZQMWIN(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::XZQMWIN)
    , _paras({})
    , _gong9(_paras)
    , _fangan(_gong9)

{
    ui->setupUi(this);


    _qmdjwin = new QMDJWIN(nullptr, _gong9);
    _qmdjwin->setWindowState(_qmdjwin->windowState() | Qt::WindowMaximized);

    _wylqwin = new WYLQWIN();
    // _wylqwin->setWindowState(_wylqwin->windowState() | Qt::WindowMaximized);

    _qmfawin = new FANGANWIN(nullptr, _fangan);

    ui->jiaComboBox->addItem(ZHU(ZHU::SHII).name(), ZHU::SHII);
    ui->jiaComboBox->addItem(ZHU(ZHU::RIII).name(), ZHU::RIII);
    ui->jiaComboBox->addItem(ZHU(ZHU::YUEE).name(), ZHU::YUEE);
    ui->jiaComboBox->addItem(ZHU(ZHU::NIAN).name(), ZHU::NIAN);

    ui->yydunzdyComboBox->addItem("阴遁", 0);
    ui->yydunzdyComboBox->addItem("阳遁", 1);

    ui->dingjuComboBox->addItem("张氏", QMGONG9::ZHANGSHI);
    ui->dingjuComboBox->addItem("茅山", QMGONG9::MAOSHAN);
    ui->dingjuComboBox->addItem("拆补", QMGONG9::CHAIBU);
    ui->dingjuComboBox->addItem("置闰", QMGONG9::ZHIRUN);
    ui->dingjuComboBox->addItem("阴盘", QMGONG9::YINPAN);
    ui->dingjuComboBox->addItem("指定", QMGONG9::ZHIDING);

    ui->juzdyComboBox->addItem("一局", 1);
    ui->juzdyComboBox->addItem("二局", 2);
    ui->juzdyComboBox->addItem("三局", 3);
    ui->juzdyComboBox->addItem("四局", 4);
    ui->juzdyComboBox->addItem("五局", 5);
    ui->juzdyComboBox->addItem("六局", 6);
    ui->juzdyComboBox->addItem("七局", 7);
    ui->juzdyComboBox->addItem("八局", 8);
    ui->juzdyComboBox->addItem("九局", 9);

    ui->jijuzdyComboBox->addItem("不寄", 0);
    ui->jijuzdyComboBox->addItem("一宫", 1);
    ui->jijuzdyComboBox->addItem("二宫", 2);
    ui->jijuzdyComboBox->addItem("三宫", 3);
    ui->jijuzdyComboBox->addItem("四宫", 4);
    ui->jijuzdyComboBox->addItem("五宫", 5);
    ui->jijuzdyComboBox->addItem("六宫", 6);
    ui->jijuzdyComboBox->addItem("七宫", 7);
    ui->jijuzdyComboBox->addItem("八宫", 8);
    ui->jijuzdyComboBox->addItem("九宫", 9);

    loadcfg();
    ui->statusBar->showMessage("銝㔉奇门仅供学习、演示、娱乐，无决策意义，不对任何结论作保证");
}

XZQMWIN::~XZQMWIN()
{
    savecfg();
    delete _qmdjwin;
    delete _wylqwin;
    delete _qmfawin;
    delete ui;
}

bool XZQMWIN::loadcfg()
{
    QJsonDocument jsonDoc;

    QFile qfile(QMCFGJSONFILE);

    if(!qfile.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    jsonDoc = QJsonDocument::fromJson(qfile.readAll());

    qfile.close();

    if (jsonDoc.isNull())
        return false;

    if(jsonDoc.isEmpty())
        return false;

    _jsonObj = jsonDoc.object();

    const QJsonObject&& json_fangan = _jsonObj[QMFA].toObject();
    QJsonArray&& json_arr = json_fangan[QMARRAY].toArray();

    for(int i = 0; i < json_arr.count(); ++i)
    {
        const QJsonObject&& obj = json_arr[i].toObject();
        ui->fanganComboBox->addItem(obj[QMINAME].toString(), obj[QMVALUE].toInteger());
    }

    ui->fanganComboBox->setCurrentIndex(json_fangan[QMINDEX].toInt());

    _paras._jia = _jsonObj[QMJIA].toObject()[QMINDEX].toInt();
    _paras._jijuzdy = _jsonObj[QMJIJUZDY].toObject()[QMINDEX].toInt();
    _paras._dingju = _jsonObj[QMDINGJU].toObject()[QMINDEX].toInt();
    _paras._yydunzdy = _jsonObj[QMYYDUN].toObject()[QMINDEX].toInt();
    _paras._juzdy = _jsonObj[QMJUZDY].toObject()[QMINDEX].toInt();

    if(!_fangan.load(ui->fanganComboBox->currentData().toLongLong()))
    {
        QMessageBox::information(this, "加载提示", "方案不存在或无效");
    }

    ui->jiaComboBox->setCurrentIndex(_paras._jia);
    ui->jijuzdyComboBox->setCurrentIndex(_paras._jijuzdy);
    ui->dingjuComboBox->setCurrentIndex(_paras._dingju);
    ui->yydunzdyComboBox->setCurrentIndex(_paras._yydunzdy);
    ui->juzdyComboBox->setCurrentIndex(_paras._juzdy);
    return true;
}

bool XZQMWIN::savecfg()
{
    QJsonDocument jsonDoc;

    QFile qfile(QMCFGJSONFILE);

    if(!qfile.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QJsonObject&& jsonJIA = _jsonObj[QMJIA].toObject();
    jsonJIA [QMINDEX] = (int)_paras._jia;
    _jsonObj[QMJIA] = jsonJIA;

    QJsonObject&& jsonYYDUN = _jsonObj[QMYYDUN].toObject();
    jsonYYDUN [QMINDEX] = (int)_paras._yydunzdy;
    _jsonObj[QMYYDUN] = jsonYYDUN;

    QJsonObject&& jsonDINGJU = _jsonObj[QMDINGJU].toObject();
    jsonDINGJU [QMINDEX] = (int)_paras._dingju;
    _jsonObj[QMDINGJU] = jsonDINGJU;

    QJsonObject&& jsonJUZDY = _jsonObj[QMJUZDY].toObject();
    jsonJUZDY [QMINDEX] = _paras._juzdy;
    _jsonObj[QMJUZDY] = jsonJUZDY;

    QJsonObject&& jsonJIJUZDY = _jsonObj[QMJIJUZDY].toObject();
    jsonJIJUZDY [QMINDEX] = _paras._jijuzdy;
    _jsonObj[QMJIJUZDY] = jsonJIJUZDY;

    QJsonObject&& jsonTIAO = _jsonObj[QMTIAO].toObject();
    _jsonObj[QMTIAO] = jsonTIAO;

    QJsonObject&& jsonFANGAN = _jsonObj[QMFA].toObject();
    jsonFANGAN [QMINDEX] = ui->fanganComboBox->currentIndex();
    _jsonObj[QMFA] = jsonFANGAN;

    jsonDoc.setObject(_jsonObj);

    QByteArray jsons = jsonDoc.toJson();

    qfile.write(jsons);

    qfile.close();

    return true;
}


void XZQMWIN::on_glDateTimeEdit1_dateTimeChanged(const QDateTime &dateTime)
{
    if(ui->wylqCheckBox1->checkState())
    {
        _wylqwin->display(dateTime, ui->glDateTimeEdit2->dateTime());
        _wylqwin->show();

        _duan = "五运六气";

        _duan += "\n使用时辰： ";

        addTimeInfo(dateTime, _duan);

        _duan += "\n诊断时辰： ";

        addTimeInfo(ui->glDateTimeEdit2->dateTime(), _duan);

        // _duan += "";//待添加

        ui->duanTextBrowser->setText(QString::fromUtf8(_duan));

        this->raise();
    }
}


void XZQMWIN::on_decDayToolButton1_clicked()
{
    QDateTime dateTime = ui->glDateTimeEdit1->dateTime();
    ui->glDateTimeEdit1->setDateTime(dateTime.addDays(-1));
}


void XZQMWIN::on_incDayToolButton1_clicked()
{
    QDateTime dateTime = ui->glDateTimeEdit1->dateTime();
    ui->glDateTimeEdit1->setDateTime(dateTime.addDays(1));
}


void XZQMWIN::on_resetDateTimePushButton1_clicked()
{
    ui->glDateTimeEdit1->setDateTime(QDateTime({2000,1,1},{0,0,0}));
}


void XZQMWIN::on_curDateTimePushButton1_clicked()
{
    ui->glDateTimeEdit1->setDateTime(QDateTime::currentDateTime());
}


void XZQMWIN::on_syncTimePushButton1_clicked()
{
    ui->glDateTimeEdit1->setDateTime(ui->glDateTimeEdit2->dateTime());
}

void XZQMWIN::on_glDateTimeEdit2_dateTimeChanged(const QDateTime &dateTime)
{
    if(ui->qmdjCheckBox2->checkState())
    {
        LIFA lf = LIFA::fromgl(dateTime);
        int ju,yy;
        GAN10 qi, luo;

        _paras._jia = ui->jiaComboBox->currentData().toInt();
        _paras._dingju = ui->dingjuComboBox->currentData().toUInt();
        _paras._yydunzdy = ui->yydunzdyComboBox->currentData().toInt();
        _paras._juzdy = ui->juzdyComboBox->currentData().toInt();
        _paras._jijuzdy = ui->jijuzdyComboBox->currentData().toInt();

        _gong9.prepare(lf);

        if(QMGONG9::ZHIDING == _paras._dingju)
        {
            yy = _paras._yydunzdy;
            ju = _paras._juzdy;
        }
        _gong9.gongjiju(_paras._jijuzdy);

        switch (_paras._jia) {
        case (int)ZHU::SHII:
            _gong9.shijia( ju, yy, qi, luo );
            break;
        case (int)ZHU::RIII:
            _gong9.rijia( ju, yy, qi, luo );
            break;
        case (int)ZHU::YUEE:
            _gong9.yuejia( ju, yy, qi, luo );
            break;
        case (int)ZHU::NIAN:
            _gong9.nianjia( ju, yy, qi, luo );
            break;
        default:
            break;
        }

        _qmdjwin->paipanxianshi(ju, yy, qi, luo, lf.bazi());

        this->raise();

        qmdjDuan(ui->glDateTimeEdit1->dateTime(), dateTime);
    }
}


void XZQMWIN::on_decDayToolButton2_clicked()
{
    QDateTime dateTime = ui->glDateTimeEdit2->dateTime();
    ui->glDateTimeEdit2->setDateTime(dateTime.addDays(-1));
}


void XZQMWIN::on_incDayToolButton2_clicked()
{
    QDateTime dateTime = ui->glDateTimeEdit2->dateTime();
    ui->glDateTimeEdit2->setDateTime(dateTime.addDays(1));
}

void XZQMWIN::on_resetDateTimePushButton2_clicked()
{
    ui->glDateTimeEdit2->setDateTime(QDateTime({2000,1,1},{0,0,0}));
}

void XZQMWIN::on_curDateTimePushButton2_clicked()
{
    ui->glDateTimeEdit2->setDateTime(QDateTime::currentDateTime());
}


void XZQMWIN::on_syncTimePushButton2_clicked()
{
    ui->glDateTimeEdit2->setDateTime(ui->glDateTimeEdit1->dateTime());
}


void XZQMWIN::addTimeInfo(const QDateTime &dateTime, QByteArray& str)
{
    int dy;
    char buf[1024];
    WUXING5::SHENGKE sk;
    LIFA lf = LIFA::fromgl(dateTime);
    const BAZI& bz = lf.bazi();
    XZGONG* gong;

    dy = lf.dayun()+1;
    gong = gong9_gid_gong(dy);
    XKFS::XING9 x9( gong->_xu );

    str += dateTime.toString("公元 yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒\n").toUtf8();

    snprintf(buf, sizeof(buf), "【 夏历 %s | %s 】【 %s | %s%s%s%s 大运 】\n【 %s 】",
             lf.nlzf(LIFA::RI | LIFA::YUE | LIFA::NIAN),
             lf.jieqiname(),
             x9.name(),
             SHUZI(dy).name(),
             x9.clr(),
             gong->gua2().name(),
             gong->wx5().name(),
             lf.bazi().name());
    str += buf;

    str += "【 ";
    sk = bz._n._g.wx5() - bz._r._g.wx5();
    str += bz._n._g.name();
    str += sk.name();
    str += bz._r._g.name();

    str += " ";
    sk = bz._y._g.wx5() - bz._r._g.wx5();
    str += bz._y._g.name();
    str += sk.name();
    str += bz._r._g.name();

    str += " ";
    sk = bz._s._g.wx5() - bz._r._g.wx5();
    str += bz._s._g.name();
    str += sk.name();
    str += bz._r._g.name();

    str += " || ";

    sk = bz._n._z.wx5() - bz._r._z.wx5();
    str += bz._n._z.name();
    str += sk.name();
    str += bz._r._z.name();

    str += " ";
    sk = bz._y._z.wx5() - bz._r._z.wx5();
    str += bz._y._z.name();
    str += sk.name();
    str += bz._r._z.name();

    str += " ";
    sk = bz._s._z.wx5() - bz._r._z.wx5();
    str += bz._s._z.name();
    str += sk.name();
    str += bz._r._z.name();
    str += " 】\n";

    return;
}


void XZQMWIN::closeEvent(QCloseEvent *)
{
    QApplication::exit();
}

void XZQMWIN::on_banToolButton_clicked()
{
    const char* title = "关于";
    const char* str = "版本：" XZQM_VERSION "\n\n"
                      "版权：开源/公版\n\n"
                      "源码：" XZQM_CODEURL "\n\n"
                      "作者：清河张\n\n编译时间："
                    __DATE__ "  "  __TIME__;

    QMessageBox msgbox(QMessageBox::Information, title, str, QMessageBox::NoButton, this);
    msgbox.addButton("晓矣", QMessageBox::YesRole);
    msgbox.setIconPixmap(QPixmap(QString::fromUtf8(":/icon/main/zhang.png")));
    msgbox.exec();
}

void XZQMWIN::on_copyToolButton_clicked()
{
    QApplication::clipboard()->setText(ui->duanTextBrowser->toPlainText());
    QMessageBox msgbox(QMessageBox::Information, "复制成功", "直接粘贴", QMessageBox::NoButton, this);
    msgbox.addButton("晓矣", QMessageBox::YesRole);
    msgbox.exec();
}

void XZQMWIN::on_dayingToolButton_clicked()
{

}


void XZQMWIN::on_clearToolButton_clicked()
{
    ui->dingzhuPlainTextEdit->clear();
}


void XZQMWIN::qmdjDuan(const QDateTime &dateTime1, const QDateTime &dateTime2)
{
    _duan = "銝㔉弄玄四不卜：\n—— | 会易免卜  明朗莫卜  小事慎卜  作恶拒卜\n"
            "\n命主时辰： ";

    addTimeInfo(dateTime1, _duan);

    _duan += "\n起局时辰： ";

    addTimeInfo(dateTime2, _duan);

    _duan += _gong9.chuduan();

    _duan += _fangan.duan(LIFA::fromgl(dateTime1));

    _qmdjwin->ysshow( _fangan.ysmap());

    _duan += "\n\n----銝㔉奇门仅供学习、演示、娱乐----\n\n看盘时间：\n";

    _duan += QDateTime::currentDateTime().toString("yyyy-MM-dd/HH:mm:ss\n").toUtf8();

    ui->duanTextBrowser->setText(QString::fromUtf8(_duan));
}


void XZQMWIN::on_dingzhuToolButton_clicked()
{
    QString jiexi;
    jiexi = QString::fromUtf8(_duan);
    jiexi += "\n断局补充观点：\n";
    jiexi += ui->dingzhuPlainTextEdit->toPlainText();
    jiexi += "\n\n----以上补充仅个人观点----\n";
    ui->duanTextBrowser->setText(jiexi);
}

void XZQMWIN::on_dingjuComboBox_currentIndexChanged(int index)
{
    if(QMGONG9::ZHIDING == ui -> dingjuComboBox->itemData(index).toUInt())
    {
        ui->yydunzdyComboBox->show();
        ui->juzdyComboBox->show();
    }
    else
    {
        ui->yydunzdyComboBox->hide();
        ui->juzdyComboBox->hide();
    }
}

void XZQMWIN::on_addFanganToolButton_clicked()
{
    QString name;
    int ret;
    qint64 id;

    id = QDateTime::currentMSecsSinceEpoch();
    _qmfawin->load(id);
    _qmfawin->exec();

    ret = _qmfawin->result();
    if(ret < 0)
        return;

    name = _qmfawin->name();
    ui->fanganComboBox->addItem(name, id);

    QJsonObject&& jsonFANGAN = _jsonObj[QMFA].toObject();
    QJsonArray&& jsonArr = jsonFANGAN[QMARRAY].toArray();
    QJsonObject jsonRcd;
    jsonRcd[QMINAME] = name;
    jsonRcd[QMVALUE] = id;
    jsonArr += jsonRcd;
    jsonFANGAN [QMARRAY] = jsonArr ;
    _jsonObj[QMFA] = jsonFANGAN;
    savecfg();
}


void XZQMWIN::on_editFanganToolButton_clicked()
{
    int index;
    qint64 id;
    QString name;

    index = ui->fanganComboBox->currentIndex();
    id = ui->fanganComboBox->itemData(index).toLongLong();

    _qmfawin->load(id);
    _qmfawin->exec();

    name = _qmfawin->name();
    ui->fanganComboBox->setItemText(index, name);

    QJsonObject jsonFANGAN = _jsonObj[QMFA].toObject();
    QJsonArray jsonArr = jsonFANGAN[QMARRAY].toArray();
    QJsonObject jsonRcd = jsonArr[index].toObject();
    jsonRcd[QMINAME] = name;
    jsonArr[index] = jsonRcd;
    jsonFANGAN [QMARRAY] = jsonArr ;
    _jsonObj[QMFA] = jsonFANGAN;
    savecfg();
}


void XZQMWIN::on_rmFanganToolButton_clicked()
{
    int index;
    qint64 id;

    index = ui->fanganComboBox->currentIndex();
    id = ui->fanganComboBox->itemData(index).toLongLong();

    ui->fanganComboBox->removeItem(index);

    QJsonObject&& jsonFANGAN = _jsonObj[QMFA].toObject();
    QJsonArray&& jsonArr = jsonFANGAN[QMARRAY].toArray();
    jsonArr.removeAt(index);
    jsonFANGAN [QMARRAY] = jsonArr;
    _jsonObj[QMFA] = jsonFANGAN;
    savecfg();
    _fangan.remove(id);
}


void XZQMWIN::on_fanganComboBox_currentIndexChanged(int index)
{
    if(!_fangan.load(ui->fanganComboBox->itemData(index).toLongLong()))
    {
        QMessageBox::information(this, "加载提示", "方案不存在或无效");
    }
}

#undef QMCFGJSONFILE
#undef QMINDEX
#undef QMARRAY
#undef QMINAME
#undef QMVALUE
#undef QMMAP
#undef QMJIA
#undef QMYYDUN
#undef QMDINGJU
#undef QMJUZDY
#undef QMJIJUZDY
#undef QMTIAO
#undef QMFA




